package com.customization.unionpay.market.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.CloudFlashPaymentUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 营销活动事项台账的【活动是否核销】=否时，定时根据授权码获取项目充值金额并更新到外部出资活动台账中的累计充值金额字段中，调用云闪付营销开放平台提供的授权码查询接口
 */
public class SyncExternalFundingActivityInfoJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncExternalFundingActivityInfoJob.class);

    public void execute() {

        RecordSet rs = new RecordSet();

        try {

            // 营销活动事项台账表单id
            int ledgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            // 营销活动事项台账主表表名
            String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
            log.info("营销活动事项台账主表表名："+ledgerTableName);
            // 外部出资活动台账表单id
            int fundingFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "external_funding_activity_form_id"));
            // 获取外部出资活动台账主表表名
            String fundingMainTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(fundingFormId);
            log.info("获取外部出资活动台账主表表名："+fundingMainTableName);
            // 查询枚举 活动是否核销
            String selectValueNo = com.customization.unionpay.market.util.FormDataUtils.getItemValue(ledgerFormId, "hdsfhx", "否");
            log.info("活动是否核销："+selectValueNo);
            if (StrUtil.isNotBlank(selectValueNo)) {
                if (StrUtil.isNotBlank(ledgerTableName)) {
                    if (StrUtil.isNotBlank(fundingMainTableName)) {
                        String sql = "select yxpthdsqm as actAuthCode from #{tableName} where hdsfhx = ? and yxpthdsqm is not null ";
                        sql = sql.replace("#{tableName}",ledgerTableName);
                        log.info("sql:"+sql);
                        // 查询营销活动事项台账活动是否核销为否的数据
                        rs.executeQuery(sql,selectValueNo);
                        List<String> codes = new ArrayList<>();
                        while (rs.next()) {
                            String actAuthCode = Util.null2String(rs.getString("actAuthCode"));
                            if (!"".equals(actAuthCode)) {
                                if (!codes.contains(actAuthCode)) {
                                    codes.add(actAuthCode);
                                }
                            }
                        }

                        // 判断集合是否大于0
                        if (codes.size() > 0) {

                            List<List<String>> lists = FormDataUtils.splitList(codes, 1000);
                            // 最大请求授权码为1000
                            for (List<String> list : lists) {
                                // 云闪付请求
                                String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
                                log.info("返回参数：" + resultStr);

                                JSONObject resultJson = JSONObject.parseObject(resultStr);

                                String errorMessage = resultJson.getString("errorMessage");
                                if ("成功".equals(errorMessage)) {
                                    JSONArray data = resultJson.getJSONArray("data");
                                    log.info("解析data参数：" + data);
                                    if(data.size() > 0) {
                                        for (int i = 0; i < data.size(); i++) {
                                            RecordSetTrans rst = new RecordSetTrans();

                                            // 开启事务（关闭自动提交）
                                            rst.setAutoCommit(false);

                                            JSONObject single = data.getJSONObject(i);
                                            // 授权码
                                            String code = single.getString("budgetAuthCode");
                                            log.info("code:" + code);
                                            // 项目充值金额
                                            Double budgetValueChecked = "".equals(single.getString("budgetValueChecked")) ? 0 :  single.getDouble("budgetValueChecked");
                                            log.info("budgetValueChecked:" + budgetValueChecked);
                                            // 银联出资金额
                                            Double unionpayValueChecked = "".equals(single.getString("unionpayValueChecked")) ? 0 :  single.getDouble("unionpayValueChecked");
                                            log.info("unionpayValueChecked:" + unionpayValueChecked);
                                            // 外部累计充值金额 = 项目充值金额 - 银联出资金额
                                            Double externalValueChecked = budgetValueChecked - unionpayValueChecked;
                                            log.info("externalValueChecked:" + externalValueChecked);
                                            // TODO 同步资金账户类型
                                            log.info("zjzhlx：" + single.getString("AcctType") );
                                            Integer zjzhlx = single.getString("AcctType") == null ? 0 : (single.getInteger("AcctType")-1);
                                            log.info("zjzhlx:" + zjzhlx);
                                            try {

                                                StringBuilder updateSql = new StringBuilder("update ");
                                                updateSql.append(fundingMainTableName);
                                                updateSql.append(" set ljczje='");
                                                updateSql.append(externalValueChecked);
                                                updateSql.append("',");
                                                updateSql.append("zjzhlx='");
                                                updateSql.append(zjzhlx);
                                                updateSql.append("'  where yxpthdsqm = '");
                                                updateSql.append(code);
                                                updateSql.append("' ");

                                                log.info("updateSql:" + updateSql.toString());

                                                // 修改累计充值金额
                                                rst.executeUpdate(updateSql.toString());
                                                // 提交事务
                                                rst.commit();

                                            } catch (Exception e) {
                                                // 回滚
                                                rst.rollback();
                                                log.error("修改数据异常：" + e.getMessage());
                                            }
                                        }
                                    }else {
                                        log.error("云闪付根据授权码查询为空！");
                                    }
                                } else {
                                    log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
                                }
                            }
                        }
                    } else {
                        log.error("根据外部出资活动台账formId查询数据库表名失败！");
                    }
                } else {
                    log.error("根据营销活动事项台账formId查询数据库表名失败！");
                }
            } else {
                log.error("活动是否核销枚举为空或找不到！");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }
}

